﻿using apiApplication1.Models;
using EntityFrameworks.Web.Core.Attributes;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;

namespace apiApplication1.Controllers
{
    public class UserController : ApiController
    {
        #region 登录
        /// <summary>    
        ///  登录操作
        /// </summary>
        [AllowAnonymous]
        [HttpPost]
        public HttpResponseMessage Login([FromBody]LoginModel model)
        {
            var resp = Request.CreateResponse(HttpStatusCode.OK, string.Empty);
            var icache = new MemcachedCache();

            if (!string.IsNullOrWhiteSpace(model.UserName) && !string.IsNullOrWhiteSpace(model.Password))
            {
                string result = string.Empty;

                switch (model.LoginType)
                {
                    case 0: //邮箱登录
                        result = "success";
                        break;
                    case 1: //手机登陆
                        result = "1";
                        break;
                    case 4: //银行卡用户登录
                        result = "1";
                        break;
                    default:
                        throw new ArgumentException("参数不正确");
                }

                #region   登陆消息设置

                if (result.Equals("success") || result.Equals("1"))
                {

                    var token = Guid.NewGuid();
                    icache.Add(token.ToString(), model.UserName);
                    resp.Content = new StringContent("{msg:ok}", Encoding.UTF8, "text/plain");

                    #region -----在报文中设置token凭据-----
                    NameValueCollection collCookie = new NameValueCollection();
                    collCookie.Add("access_token", token.ToString());
                    collCookie.Add("user_id", model.UserName);
                    resp.Headers.AddCookies(new List<CookieHeaderValue>() { new CookieHeaderValue("token_list", collCookie) });
                    #endregion
                }
                else
                {
                    resp.Content = new StringContent("{msg:" + result + "}", Encoding.UTF8, "text/plain");
                }
                #endregion
            }
            else
            {
                resp = Request.CreateResponse(HttpStatusCode.OK, string.Empty);
                resp.Content = new StringContent("{msg:用户名密码不能为空!}", Encoding.UTF8, "text/plain");
            }
            return resp;
        }
        #endregion

    }
}
